import react, { useState, useEffect, useMemo } from 'react'
import { Button, Modal, Typography } from 'antd';
import { InbizGraph } from 'inbiz-graph';
import Cookies from 'js-cookie';
import { InbizIcon, debounce } from '@inbiz/utils';
import { GlobalRegistry } from '@inbiz/core';
import { TextWidget, getMessage } from '@inbiz/react';
import { useSearchUIState } from '../../../../store/hooks/useSearchUIState';
import { useInbiz } from '../../../../store/hooks/useInbiz';
import { useConfigEventsApi, useSearchPropsState } from '../../../../store/hooks/useSearchPropsState';
import { useSearchUIDispatch } from '../../../../store/hooks/useSearchUIDispatch';
import { useJumpResult } from '../../../../store/hooks/useJumpResult';
// 检索条件-组件
const SearchTextList = (props) => {
  const { onOpenAdSearch, controlId } = props
  const { keywords, keyword, selectShowTab, nowText } = useSearchUIState();
  const { configEvents } = useConfigEventsApi();
  const { detection } = useSearchPropsState();
  const updateUIState = useSearchUIDispatch();
  const onJumpResult = useJumpResult();
  const inbiz = useInbiz()
  // 是否显示图谱弹窗
  const [visible, $visible] = useState(false);
  // 是否全屏图谱弹窗
  const [isfullModal, $isfullModal] = useState(false);
  // 全屏高度
  const [height, $height] = useState<number>(document.body.clientHeight);
  // 全屏宽度
  const [width, $width] = useState<number>(document.body.clientWidth);
  const filList: string[] = keywords?.filter((item: any) => item && item !== '') || [];
  const [detectionWidth, $detectionWidth] = useState(0)
  // 删除关键字-触发重搜
  const del = (txt: string, idx: number) => {
    const newKeywords = keywords
      .filter((item: any) => item)
      .filter((ele, index: number) => ele !== txt || index !== idx);
    // let newKeyword =
    //   newKeywords.length && newKeywords.includes(keyword || '')
    //     ? keyword
    //     : newKeywords[newKeywords.length - 1];
    onJumpResult(newKeywords.join(''), newKeywords);
    updateUIState({
      keywords: newKeywords,
      // keyword: newKeyword,
    });
  };

  // 注册页面宽度变化事件执行方法及重算组件显示逻辑
  useEffect(() => {
    const updateSize = debounce({
      fn: () => {
        $height(document.body.clientHeight);
        $width(document.body.clientWidth);
      },
      delay: 100,
    });
    window.addEventListener('resize', updateSize);
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  const langs = {
    'zh-cn': 'zh-CN',
    'en-us': 'en-US',
    'ja': 'ja'
  }
  const getlangs = () => {
    const langType = GlobalRegistry.getDesignerLanguage() as 'zh-cn' | 'en-us' | 'ja'
    return langs[langType]
  }

  const InbizGraphProps = useMemo(() => {
    const options = {
      width: isfullModal ? width : 600,
      height: isfullModal ? height - 50 : 400,
      graphUrl: `/search/IndexSearch/GetAtlasData?token=${Cookies.get('token')}`,
      params: {
        anchor: nowText || '',
        step: 2,
        type: 'entity',
        offset: 0,
      },
      lang: getlangs(),
      svgBoxId: 'conditionSvg',
      EDOC2_URL: '/preview.html?fileid=',
      optEvent: {
        searchDoc: (data: any) => {
          onJumpResult(data?.name || '', data?.name ? [data.name] : []);
          updateUIState({
            keyword: data?.name || '',
            keywords: [data?.name || ''],
          });
          $visible(false);
        },
      },
    };
    return configEvents.current.onInbizGraphInit?.(options) || options;
  }, [nowText, isfullModal, width, height]);

  useEffect(() => {
    if (detection) {
      const btn: any = document.querySelector(`#${controlId}_searchBtn`);
      const searchBody: any = document.querySelector(`#${controlId}_searchBody`);
      const searchResultBtn = document.querySelector(`#${controlId}_searchResultBtn`);
      if (!searchBody) {
        return
      }
      if (searchResultBtn) {
        $detectionWidth(searchBody.clientWidth - searchResultBtn.clientWidth)
      } else {
        $detectionWidth(searchBody.clientWidth - btn.clientWidth)
      }

    }

  }, [detection])

  return (
    <div className='detectionContainer' style={{
      flexDirection: detection ? 'row' : 'row-reverse'
    }}>
      {detection && (
        <div className="search-texts-box"
          style={{
            width: detectionWidth,
            lineHeight: '30px'
          }}>
          {/** 按照英文的宽度来的 */}
          <Typography.Text style={{ maxWidth: 111 }} ellipsis title={getMessage('SearchEngine.retrievalCriteria')}>
            <TextWidget>SearchEngine.retrievalCriteria</TextWidget>：
          </Typography.Text>
          <div className="search-txt-list" style={{ width: detectionWidth - 115 }}>
            {filList.map((item: string, idx: number) => {
              return (
                <div className="search-txt-item" key={`${item}${idx}`}>
                  <span className="item-name" title={item}>{item}</span>
                  {filList.length !== 1 && (
                    <span className="colse-icon" onClick={() => del(item, idx)}>
                      <InbizIcon type="icon-close_filled" />
                    </span>
                  )}
                  {selectShowTab?.keywordAtlas && (
                    <InbizIcon
                      type="icon-atlas-hover"
                      onClick={() => {
                        $visible(true);
                        updateUIState({
                          nowText: item,
                        });
                      }}
                    />
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}
      {detection && (
        <Modal
          destroyOnClose
          className={
            isfullModal
              ? 'search-engine-graph-modal search-engine-graph-modal-full'
              : 'search-engine-graph-modal'
          }
          closable={false}
          title={
            <div className="search-engine-graph-modal-title">
              <Button
                key={'fullScreen'}
                type={'text'}
                icon={
                  isfullModal ? (
                    <InbizIcon type="icon-huanyuan" style={{ fontSize: 20 }} />
                  ) : (
                    <InbizIcon type="icon-ic-zuidahua" style={{ fontSize: 20 }} />
                  )
                }
                onClick={() => $isfullModal(!isfullModal)}
              />
              <Button
                key={'close'}
                type={'text'}
                icon={<InbizIcon type="icon-ic-close-bold" style={{ fontSize: 18 }} />}
                onClick={() => {
                  $visible(false);
                  $isfullModal(false);
                }}
              />
            </div>
          }
          footer={null}
          visible={visible}
        >
          <InbizGraph {...InbizGraphProps} />
        </Modal>
      )}
      {Boolean(selectShowTab?.advancedSearch) && selectShowTab?.advancedSearchStyle === 'style2' && <Button onClick={onOpenAdSearch} type="link" className="advanced-search-open-btn">
        <TextWidget>SearchEngine.advancedSearch</TextWidget>
      </Button>}
    </div>
  );
};
export default SearchTextList
